package com.zone.vehicle.superapp.view.home.home.search;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.entity.AppEntity;
import com.zone.sdk.module.comment.entity.SearchResultEntity;
import com.zone.vehicle.lib.view.utils.ImageUtil;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.databinding.SearchResultFragmentBinding;
import com.zone.vehicle.superapp.databinding.SearchResultsListItemBinding;
import com.zone.vehicle.superapp.model.HomeViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;
import com.zone.vehicle.superapp.view.common.enums.ActionEnum;
import com.zone.vehicle.superapp.view.common.listener.ActionListener;
import com.zone.vehicle.superapp.view.util.NumberUtil;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.zone.vehicle.superapp.view.common.enums.ActionEnum.ACTION_FOCUS_CLEARED;
import static com.zone.vehicle.superapp.view.common.enums.ActionEnum.ACTION_SEARCH;
import static com.zone.vehicle.superapp.view.home.HomeFragment.APP_DETAIL_FRAGMENT;

public class SearchResultFragment extends BaseFragment {

    private static final String TAG = SearchResultFragment.class.getSimpleName();

    private SearchResultFragmentBinding binding;

    protected HomeViewModel viewModel;

    private InnerAppAdapter innerAppAdapter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = SearchResultFragmentBinding.inflate(inflater);
        init();
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        showErrorPage(0);
    }

    private void init(){
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(HomeViewModel.class);
        innerAppAdapter = new InnerAppAdapter(new ArrayList<>());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.setAdapter(innerAppAdapter);
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer() {
            @Override
            public void onChanged(Object o) {
                showErrorPage(3);
            }
        });
        viewModel.getSearchData().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d(TAG,"onChanged="+s);
                viewModel.indexSearch(requireContext(), s);
            }
        });
        viewModel.getSearchAppList().observe(getViewLifecycleOwner(), new Observer<List<SearchResultEntity>>() {
            @Override
            public void onChanged(List<SearchResultEntity> appEntities) {
                innerAppAdapter.setData(appEntities);
                innerAppAdapter.notifyDataSetChanged();
                if (ObjectUtils.isEmpty(appEntities)){
                    showErrorPage(1);
                }
            }
        });
        addListener(new ActionListener(){

            @Override
            public boolean onAction(ActionEnum action) {
                Log.d(TAG,"onAction="+action);
                if (action == ACTION_SEARCH){
                    return true;
                }else if (action == ACTION_FOCUS_CLEARED){
                }
                return false;
            }

            @Override
            public boolean onPageChanged(String pageName) {
                return false;
            }
        });
    }

    private class InnerAppAdapter extends RecyclerView.Adapter<InnerAppAdapter.ViewHolder>{

        private List<SearchResultEntity> data;

        private SearchResultsListItemBinding binding;

        public InnerAppAdapter(List<SearchResultEntity> data) {
            this.data = data;
        }

        public void setData(List<SearchResultEntity> data) {
            this.data = data;
        }

        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            binding = SearchResultsListItemBinding.inflate(LayoutInflater.from(parent.getContext()));
            return new ViewHolder(binding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NotNull ViewHolder holder, int position) {
            if (ObjectUtils.isEmpty(data)){
                return;
            }
            SearchResultEntity resultEntity = data.get(position);
            binding.name.setText(resultEntity.getName());
//            //设置图片大小
//            RoundedCorners roundedCorners = new RoundedCorners(50);
//            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners)
//                    .placeholder(new ColorDrawable(Color.GRAY))//设置占位图
////                    .error(R.mipmap.logo_app)//设置异常图片
//                    .override(300, 300);//降低内存消耗
//            Glide.with(holder.itemView.getContext())
//                    .asBitmap()
//                    .load(resultEntity.getLogo())
//                    .apply(options)
//                    .into(holder.icon);
            ImageUtil.load(activity, holder.icon, resultEntity.getLogo());
            holder.description.setText(resultEntity.getDesc());

            if (StringUtils.isNotEmpty(resultEntity.getType()) && resultEntity.getType().equals(AppTypeEnum.APP.getName())){
                String size = StringUtils.isNoneEmpty(resultEntity.getSize())?resultEntity.getSize():"0 M";
                holder.desc.setText(NumberUtil.getNumber(resultEntity.getDownloadsNum())+" 下载 | "+size);
            } else {
                holder.desc.setText(NumberUtil.getNumber(resultEntity.getDownloadsNum())+" 下载 ");
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppDetailEntity appEntity = new AppDetailEntity();
                    appEntity.setCode(resultEntity.getGoodsCode());
//                    viewModel.setCurrentApp(appBean);
                    viewModel.setCurrentAppEntity(appEntity);
                    changePage(APP_DETAIL_FRAGMENT);
                }
            });
        }

        @Override
        public int getItemCount() {
            return ObjectUtils.isNotEmpty(data)?data.size():0;
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private final ImageView icon;
            private final TextView name;
            private final TextView description;
            private final TextView desc;
            private final TextView size;

            public ViewHolder(View itemView) {
                super(itemView);
                icon = itemView.findViewById(R.id.icon);
                name = itemView.findViewById(R.id.name);
                description = itemView.findViewById(R.id.description);
                desc = itemView.findViewById(R.id.desc);
                size = itemView.findViewById(R.id.size);
            }
        }
    }

    @Override
    public void showErrorPage(int type){
        switch (type){
            case 1://no data
                binding.recyclerView.setVisibility(View.GONE);
                binding.errorLayout.setVisibility(View.VISIBLE);
                binding.top.setVisibility(View.VISIBLE);
                binding.top.setText(R.string.error_no_data);
                binding.bottom.setVisibility(View.GONE);
                break;
            case 2://no wifi
                binding.recyclerView.setVisibility(View.GONE);
                binding.errorLayout.setVisibility(View.VISIBLE);
                binding.top.setVisibility(View.VISIBLE);
                binding.top.setText(R.string.error_no_wifi);
                binding.bottom.setVisibility(View.VISIBLE);
                break;
            case 3://error server
                binding.recyclerView.setVisibility(View.GONE);
                binding.errorLayout.setVisibility(View.VISIBLE);
                binding.top.setVisibility(View.VISIBLE);
                binding.top.setText(R.string.error_server);
                binding.bottom.setVisibility(View.VISIBLE);
                break;
            default:
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.errorLayout.setVisibility(View.GONE);
                binding.top.setVisibility(View.GONE);
                binding.bottom.setVisibility(View.GONE);
        }
        binding.bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ObjectUtils.isNotEmpty(viewModel.getSearchData().getValue())) {
                    viewModel.indexSearch(requireContext(), viewModel.getSearchData().getValue().toString());
                }
            }
        });

    }
}